


from flask import Blueprint, request, jsonify, g
import psycopg2.extras

from db_utils.postgresql_connection import PostgreSQLConnection

from db_utils.repositories.users_table import UsersTable
from db_utils.repositories.tokens_table import TokensTable

from db_utils.repositories.roles_table import RolesTable
from db_utils.repositories.user_roles_table import UserRolesTable

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

user_blueprint = Blueprint('user_blueprint', __name__)


# 注册用户
@user_blueprint.route('/register_user', methods=['POST'])
def register_user():

    password = request.form.get('password')
    username = request.form.get('username')
    phone = request.form.get('phone')

    if not all([password, username, phone]):

        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    # 电话号码格式验证
    if not phone.isdigit() or len(phone)!= 11:

        return jsonify({"status": -1, "errorCode": 1005, "errorMsg": "手机号格式错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):
        users_table = UsersTable(conn, cursor)

        user_info_by_name = users_table.get_user_by_name(username)

        if user_info_by_name:

            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": "用户名已存在", "resultBody": None})
        
        user_info_by_phone = users_table.get_user_by_phone(phone)

        if user_info_by_phone:

            return jsonify({"status": -1, "errorCode": 1003, "errorMsg": "手机号已存在", "resultBody": None})

        create_result = users_table.create_user(username, phone, password) # (True, 1)

        if not create_result[0]:
            return jsonify({"status": -1, "errorCode": 1004, "errorMsg": f"注册失败: {create_result[1]}", "resultBody": None})
        else:
            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"user_id": create_result[1]}})



# 登陆 
@user_blueprint.route('/login', methods=['POST'])
def login():
    
    phone = request.form.get('phone')
    password = request.form.get('password')

    if not all([phone, password]):

        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        users_table = UsersTable(conn, cursor)
        user_info = users_table.get_user_by_phone(phone)

        if not user_info:
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": "用户不存在", "resultBody": None})

        if user_info['password'] != password:
            return jsonify({"status": -1, "errorCode": 1003, "errorMsg": "密码错误", "resultBody": None})
        
        # 生成token
        token_result = TokensTable(conn, cursor).add_token(user_info['user_id']) # (True, 'token')


        if not token_result[0]:

            return jsonify({"status": -1, "errorCode": 1004, "errorMsg": f"生成token失败: {token_result[1]}", "resultBody": None})

        # 获取角色ids
        user_roles_table = UserRolesTable(conn, cursor)
        role_ids = user_roles_table.get_role_ids_by_user_id(user_info['user_id'])

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"user_id": user_info['user_id'], "username": user_info['user_name'], "phone": user_info['phone'], "role_ids": role_ids, "avatar": None, "token": token_result[1]}})


# 获取用户信息
@user_blueprint.route('/get_user_info')
def get_user_info():
    
    with PostgreSQLConnection() as (conn, cursor):
        users_table = UsersTable(conn, cursor)
        user_info = users_table.get_user_by_id(g.user_id)

        if not user_info:
            return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "用户不存在", "resultBody": None})

        # 删除密码
        del user_info['password']

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": user_info})
    
# 更新用户信息
@user_blueprint.route('/update_user_info', methods=['POST'])
def update_user_info():
    
    user_id = g.user_id
    password = request.form.get('password')
    username = request.form.get('username')
    phone = request.form.get('phone')

    if not all([password, username, phone]):
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})
    
    # 电话号码格式验证
    if not phone.isdigit() or len(phone)!= 11:
    
        return jsonify({"status": -1, "errorCode": 1005, "errorMsg": "手机号格式错误", "resultBody": None})
    
    with PostgreSQLConnection() as (conn, cursor):
        # 更新用户信息
        # def update_user(self, user_id, user_name, phone, password):
        UsersTable(conn, cursor).update_user(user_id, username, phone, password)
    
        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "更新成功"})
        

# 获取所有用户信息
@user_blueprint.route('/get_all_users')
def get_all_users():
    
    with PostgreSQLConnection() as (conn, cursor):
        users_table = UsersTable(conn, cursor)
        users = users_table.get_all_users()

        count = users_table.get_user_count()

        if not users:
            return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "用户不存在", "resultBody": None})

        # 删除密码
        for user in users:
            del user['password']
            # user_name 变成 username
            user['username'] = user.pop('user_name')

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": users, "count": count}})


